<template>
  <md-nav-bar :title="`${data.pageType === 'add' ? '新增' : '编辑'}常用人`" />
  <view class="container">
    <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
      <uni-forms-item label="证件类型" name="id_type" required :clear="false">
        <view class="form-item" style="padding: 0">
          <uni-data-select v-model="data.formData.id_type" :localdata="data.idTypeList"></uni-data-select>
        </view>
      </uni-forms-item>
      <uni-forms-item :label="data.formData.id_type == 1 ? '身份证信息面' : '证件照'" name="front_img" required>
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.front_img"
            @select="e => handleUpload(e, 'front_img')">
            <md-icon type="bg" name="id_front" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item v-if="data.formData.id_type == 1" label="身份证国徽面" name="back_img" required>
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.back_img"
            @select="e => handleUpload(e, 'back_img')">
            <md-icon type="bg" name="id_back" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item label="姓名" name="truename" required>
        <uni-easyinput type="text" v-model="data.formData.truename" placeholder="请输入姓名" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="性别" name="sex" required>
        <view class="form-item">
          <uni-data-checkbox v-model="data.formData.sex" :localdata="data.sex"></uni-data-checkbox>
        </view>
      </uni-forms-item>
      <uni-forms-item label="证件号" name="idcard" required>
        <uni-easyinput type="text" v-model="data.formData.idcard" placeholder="请输入证件号" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="出生日期" name="birth" required>
        <uni-datetime-picker type="date" :clear-icon="false" v-model="data.formData.birth" :border="false" />
      </uni-forms-item>
      <uni-forms-item label="年龄" name="age" required>
        <uni-easyinput type="number" v-model="data.formData.age" placeholder="请输入年龄" :input-border="false" />
      </uni-forms-item>
      <!-- <uni-forms-item label="上传体检报告" name="report_img">
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            limit="1"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.report_img"
            @select="e => handleUpload(e, 'report_img')">
            <md-icon type="bg" name="mr_front" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item> -->
      <!-- <uni-forms-item label="服装尺码" name="size" required>
        <view class="form-item" style="padding: 0">
          <uni-data-select v-model="data.formData.size" :localdata="data.sizeList" />
        </view>
      </uni-forms-item> -->
      <uni-forms-item label="联系电话" name="mobile" required>
        <uni-easyinput type="text" v-model="data.formData.mobile" placeholder="请输入联系电话" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="紧急联系人" name="contact" required>
        <uni-easyinput
          type="text"
          v-model="data.formData.contact"
          placeholder="请输入紧急联系人"
          :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="紧急联系人电话" name="contact_mobile" required>
        <uni-easyinput
          type="text"
          v-model="data.formData.contact_mobile"
          placeholder="请输入紧急联系人电话"
          :input-border="false" />
      </uni-forms-item>
    </uni-forms>
    <md-button
      :color="data.configInfo.button_color1 || '#d92121'"
      :text-color="data.configInfo.button_color1_text || '#ffffff'"
      class="submit m-top-40"
      @click="submit">
      提交
    </md-button>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
// 接口
import { check_ocr_identity, uploadImage, userSignAdd, userSignConfig, userSignEdit } from '@/api';
import { onLoad } from '@dcloudio/uni-app';
// 工具
import { formatSignValue, formatSignSubmitValue } from '@/pages/registration/util';
import { Toast } from '@/utils/util';

const data = reactive<any>({
  pageType: '', // add | edit
  formData: {
    truename: '',
    idcard: '',
    sex: 1,
    birth: null,
    id_type: 1,
    age: '',
    num: '',
    size: '',
    mobile: '',
    contact: '',
    contact_mobile: '',
    front_img: {},
    back_img: {},
    report_img: {},
  },
  rules: {
    truename: {
      rules: [
        {
          required: true,
          errorMessage: '请输入姓名',
        },
      ],
    },
    idcard: {
      rules: [
        {
          required: true,
          errorMessage: '请输入身份证',
        },
      ],
    },
    sex: {
      rules: [
        {
          required: true,
          errorMessage: '请选择性别',
        },
      ],
    },
    birth: {
      rules: [
        {
          required: true,
          errorMessage: '请选择出生日期',
        },
      ],
    },
    age: {
      rules: [
        {
          required: true,
          errorMessage: '请输入年龄',
        },
      ],
    },
    id_type: {
      rules: [
        {
          required: true,
          errorMessage: '请选择证件类型',
        },
      ],
    },
    // size: {
    //   rules: [
    //     {
    //       required: true,
    //       errorMessage: '请选择服装尺寸',
    //     },
    //   ],
    // },
    mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入联系电话',
        },
      ],
    },
    contact: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人',
        },
      ],
    },
    contact_mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人电话',
        },
      ],
    },
    front_img: {
      rules: [{ required: true, errorMessage: '请上传身份证信息面' }],
    },
    back_img: {
      rules: [{ required: true, errorMessage: '请上传身份证国徽面' }],
    },
  },
  sex: [
    {
      text: '男',
      value: 1,
    },
    {
      text: '女',
      value: 2,
    },
  ],
  idTypeList: [],
  sizeList: [],
  configInfo: {},
});

const form = ref(null);

// 触发提交表单
const submit = async () => {
  try {
    const res = await form.value?.validate();
    // console.log('表单数据信息：', res);
    if (data.pageType === 'add') {
      // 新增
      userSignAdd({ ...formatSignSubmitValue(res) }).then(res => {
        uni.showModal({
          title: '提示',
          content: res?.msg || '新增成功',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.navigateBack();
            }
          },
        });
      });
    } else {
      // 编辑
      userSignEdit({
        ...formatSignSubmitValue({ ...res, id: data.formData?.id }),
      }).then(res => {
        uni.showModal({
          title: '提示',
          content: res?.msg || '编辑成功',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.navigateBack();
            }
          },
        });
      });
    }
  } catch (e) {
    //TODO handle the exception
    console.log('表单错误信息：', e);
    e?.length && Toast(e?.[e?.length - 1]?.errorMessage);
  }
};

/**
 * 上传相关
 */
const handleUpload = (e: any, type: string) => {
  // console.log('选择文件：', e);
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  uploadImage({ filePath: tempFilePaths[0], formData: { category: 'user_sign' } }).then(async res => {
    // console.log(res);
    const obj = {
      url: res?.data?.url,
      extname: 'png',
      name: type + '.png',
    };
    if ([1, 2, 3, 4, 9].includes(data.formData.id_type) && type === 'front_img') {
      const info = await fetchCheckOcrIdentity(res?.data?.url);
      data.formData = { ...data.formData, ...info };
    }
    data.formData[type] = obj;
    uni.hideLoading();
  });
};

/**
 * 接口相关
 */
const fetchuserSignConfig = async () => {
  try {
    const res = await userSignConfig();
    data.idTypeList = res.data?.id_type || [];
  } catch (error) {}
};

// 校验身份证图片
const fetchCheckOcrIdentity = async (front_img: string) => {
  try {
    const res = await check_ocr_identity({ front_img, id_type: data.formData.id_type });
    return res.data;
  } catch (error) {}
  return undefined;
};

onLoad(option => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
  }
  // console.log(option);
  data.pageType = option?.type;
  if (option?.info) {
    let _info = JSON.parse(option.info);
    data.formData = formatSignValue(_info);
  }
  // data.info = op
  fetchuserSignConfig();
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .form-item {
    background: white;
    border-radius: 10rpx;
    padding: 10rpx 0 10rpx 10px;
  }
  .form-item-content {
    padding: 16rpx;
    background: white;
  }
  .form-item-row {
    position: relative;
    .del-button {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .add {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    color: #b3b3b3;
    font-size: 28rpx;
    text-align: center;
  }
}
</style>
